#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.template import loader, Context
import datetime

from blog.models import Student,Teacher,Group

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self):
        return "hello world"


def index(request):
    t = loader.get_template("index.html")

    person = Person("zhangsan", 19)
    book_list = ['python', 'ruby', 'java', 'c']
    date_time = datetime.datetime.now()

    data = {
        "title": "zhangsan",
        "user": person,
        "userItems": {
            "name": 'zhangsan',
            'age': 19,
            'sex': 'man'
        },
        "book": book_list,
        'date': date_time
    }
    c = Context(data)
    return HttpResponse(t.render(c))


# return HttpResponse("<h1>hello world</h1>")

def time(request):
    t = loader.get_template('time.html')
    id = request.GET.get('id')
    str = request.GET.get('str')
    c = Context({
        'time': datetime.datetime.now(),
        'id': id,
        'str': str
    })
    return HttpResponse(t.render(c))


def foo(request, id, name):
    t = loader.get_template('foo.html')
    data = {
        'id': id,
        'name': name
    }
    c = Context(data)
    return HttpResponse(t.render(c))


def bar(request, id, name):
    t = loader.get_template('bar.html')
    data = {
        'id': id,
        'name': name
    }
    c = Context(data)
    return HttpResponse(t.render(c))


def studentList(request):
    t = loader.get_template('student_list.html')

    # 获取数据库的方法

    # student_list = Student.objects.all().order_by("-age","-id").filter(age=18) age__gt 大于 age__gte 大于等于
    # student_list = Student.objects.all().filter(age__gt=18)            name__contains 相当于like
    # student_list = Student.objects.all().filter(name__contains="张")
    # student_list = Student.objects.get(id = 2) #获得单个对象

    # 修改数据库的方法    单个更新
    # student = Student.objects.get(id=2)
    # student.name = "单个"
    # student.age = 16
    # student.save()

    # 数据库 批量更新
    # Student.objects.filter(age__lte=16).update(name='xyz')

    # 数据库的增加
    # newStu = Student(name="zhangsan",age=10,inttime="2012-12-2",sex='1')
    # newStu.save()

    # # 单个数据库的删除
    # student = Student.objects.get(id=2)
    # student.delete()
    # 批量数据库删除
    # Student.objects.all().filter(age__gt=18).delete()

    # 关联外键  学生关联老师
    # student_list = Student.objects.all()
    # 关联外键 老师关联学生
    # teacher = Teacher.objects.get(id=2)
    # student_list = teacher.student_set.all()

    # 关联外键  删除
    # teacher = Teacher.objects.get(id=2)
    # teacher.student_set.create(name="全额")
    # student = Student(name='tome')
    # teacher.student_set.add(student)


    # 多对多 关系


    group = Group.objects.get(id=2)
    student_list = group.members.all()
    data = {
        'studentList': student_list
    }
    c = Context(data)
    return HttpResponse(t.render(c))
